package com.cuit.house.service;

import com.alibaba.fastjson.JSON;
import com.cuit.house.common.UserException;
import com.cuit.house.mapper.UserMapper;
import com.cuit.house.model.User;
import com.cuit.house.utils.BeanHelper;
import com.cuit.house.utils.HashUtils;
import com.google.common.base.Strings;
import com.zhenzi.sms.ZhenziSmsClient;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Value("${message.apiUrl}")
    private String apiUrl;

    @Value("${message.appId}")
    private String appId;

    @Value("${message.appSecret}")
    private String appSecret;

    @Value("${file.prefix}")
    private String imgPrefix;

    public User getUserById(Long id) {
        //这是rediskey
        String key = "user:" + id;
        //根据key获取redis的值
        String json = redisTemplate.opsForValue().get(key);
        User user = null;
        //判断redis中是否有这个值
        if (Strings.isNullOrEmpty(json)) {
            //如果没有 取数据库的值
            user = userMapper.findOne(Math.toIntExact(id));
            //设置图片前缀
            user.setAvatar(imgPrefix + user.getAvatar());
            //查询出来的用户转换成string字符串 好往redis存储
            String string = JSON.toJSONString(user);
            redisTemplate.opsForValue().set(key, string);
            redisTemplate.expire(key, 10, TimeUnit.MINUTES);
        } else {
            //如果有值  直接转换为user对象
            user = JSON.parseObject(json, User.class);
        }
        return user;
    }


    //添加账户
    public boolean addAccount(User user) {
        user.setPassword(HashUtils.encryPassword(user.getPassword()));
        BeanHelper.onInsert(user);
        user.setUid("@"+user.getPhonenumber()+System.currentTimeMillis());
        user.setUsername(user.getPhonenumber());
        userMapper.save(user);
        return true;
    }

    //验证验证码
    //加事务，验证错误不注册
    @Transactional
    public void enable(User user, String key) {
        String phone = redisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(phone)) {
            throw new UserException(UserException.Type.USER_NOT_FOUND, "无效的验证码");
        } else {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            user.setRegisterday(df.format(new Date()));// new Date()为获取当前系统时间
            addAccount(user);
        }
    }

    //发送短信
    public void sendRandomKey(User user) throws Exception {
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
        Map<String, String> params = new HashMap<>();
        String randomKey = RandomStringUtils.randomNumeric(4);
        redisTemplate.opsForValue().set(randomKey, user.getPhonenumber());
        redisTemplate.expire(randomKey, 1, TimeUnit.HOURS);
        params.put("message", "您的验证码是" + randomKey + "，请不要泄露给他人，十分钟后失效哦");
        params.put("number", user.getPhonenumber());
        client.send(params);
    }

    //登陆
    public User login(User query) {
        query.setPassword(HashUtils.encryPassword(query.getPassword()));
        User user = userMapper.findByPasswordAndPhonenumber(query.getPassword(), query.getPhonenumber());
        return user;
    }

    //改密码
    @Transactional
    public void change(User query, String key) {
        String phone = redisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(phone)) {
            throw new UserException(UserException.Type.USER_NOT_FOUND, "无效的验证码");
        } else {
            //验证后修改
            query.setPassword(HashUtils.encryPassword(query.getPassword()));
            userMapper.update(query.getPassword(), query.getPhonenumber());
        }
    }

    //修改个人信息
    @Transactional
    public void changeAll(User query) {
        userMapper.updateAll(query.getUsername(), query.getBirthday(), query.getAddress(), query.getAvatar(), query.getPhonenumber());
    }
}
